package com.smartStatus.security.handler;

import cn.hutool.http.HttpUtil;
import com.smartStatus.security.utils.WebUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.Charset;

/**
 * @ClassName : FormLoginFailureHandler
 * @Author : lby
 * @Date: 2021/5/6 21:43
 * @Description : 表单登陆失败拦截
 */
@Slf4j
public class FormLoginFailureHandler implements AuthenticationFailureHandler {
    /**
     * Called when an authentication attempt fails.
     *
     * @param request   the request during which the authentication attempt occurred.
     * @param response  the response.
     * @param exception the exception which was thrown to reject the authentication
     */
    @Override
    @SneakyThrows
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) {
        log.info("表单登陆失败:{}", exception.getLocalizedMessage());
        WebUtils.getResponse().sendRedirect(String.format("/token/login?error=%s"
                , HttpUtil.encodeParams(exception.getMessage(), Charset.defaultCharset())));
    }
}
